package org.seckill.service.impl;

import org.apache.commons.collections.MapUtils;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dao.cache.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillStateEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 秒杀系统的service层
 * Created by zzz on 2016/11/2.
 */
//@Component Spring的通用注解。@Service @Dao @Controller

@Service
public class SeckillServiceImpl implements SeckillService {
    //日志信息
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisDao redisDao; //redis缓存Dao
    //秒杀的dao
    @Autowired
    private SeckillDao seckillDao;
    //秒杀成功的dao
    @Autowired
    private SuccessKilledDao successKilledDao;
    //md5  盐值字符串，用于混淆MD5

    private final String slat = "akjsndkjanskdjnaposfjdjlnasdbqiwer7y9Y7yrd03e9h9";


    /**
     * 根据偏移量查询秒杀商品列表
     *
     * @return
     */
    public List<Seckill> getSeckillList() {
        return seckillDao.queryAll(0, 4);
    }

    /**
     * 根据id查询秒杀对象
     *
     * @param seckillId
     * @return
     */
    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    /**
     * 秒杀开始后暴露秒杀地址(该方法已经进过redis 缓存优化)
     * 否则是输出系统时间和秒杀时间
     *
     * @param seckillId
     * @return
     */
    public Exposer exportSeckillUrl(long seckillId) {
        //优点：缓存优化，超时的基础上维护一致性;
        //1：访问redis，从缓存中读取数据
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null) {
            //2:访问数据库
            seckill = seckillDao.queryById(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId); //数据库中查找不到，说明商品不存在
            } else {
                redisDao.putSeckill(seckill); // 从数据库中查到之后，放入redis中
            }
        }

        if (seckill == null) {
            return new Exposer(false, seckillId);
        } else {
            Date startTime = seckill.getStartTime();
            Date endTime = seckill.getEndTime();
            //系统当期时间,long类型的毫秒表示
            Date nowTime = new Date();
            if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
                return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
            }

            //转化特定字符串的过程，不可逆
            String md5 = this.getMD5(seckillId);//使用md5加密
            return new Exposer(true, md5, seckillId);

        }
    }

    /**
     * 生成md5的方法，对id进行加密
     *
     * @param seckillId
     * @return
     */
    private String getMD5(long seckillId) {
        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());

        return md5;
    }

    /**
     * 核心方法:执行秒杀的方法。
     *
     * @param seckillId
     * @param userPhone
     * @param md5
     * @return
     * @throws SeckillException
     * @throws RepeatKillException
     * @throws SeckillException
     */

    //使用注解控制事务的方法的优点：
    // 1.开发团队达成一致约定，明确标注事务方法对的编程风格
    // 2.保证事务方法的执行时间尽可能的短，不要穿插其他的网络操作比如：RPC/http请求，或者剥离到方法外部。
    // 3.并不是所有的方法，都需要事务。比如：只修改一条数据，或者是只读操作时(不需要处理高并发问题时)。
    @Transactional
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillException {
        if (md5 == null || !md5.equals(this.getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }

        try {
            //记录购买行为
            int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
            if (insertCount <= 0) {
                //重复秒杀
                throw new RepeatKillException("重复秒杀");
            } else {
                //执行秒杀逻辑: 减库存,热点商品竞争
                Date nowTime = new Date();
                int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
                if (updateCount <= 0) {
                    //表示是没有更新到数据,秒杀已结束,rollback
                    throw new SeckillCloseException("seckill is closed");
                } else {
                    //秒杀成功，commit
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
                }
            }

        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatKillException e2) {
            throw e2;
        } catch (Exception e) {
            //将所有的编译期异常全部转化为运行期异常
            throw new SeckillException("seckill inner error" + e.getMessage());
        }

    }

    /**
     * 使用存储过程，执行秒杀操作，将操作放在mysql执行，客户端只需要拿到，返回的result，判断秒杀状态
     *
     * @param seckillId
     * @param userPhone
     * @param md5
     * @return
     * @throws RepeatKillException
     * @throws SeckillCloseException
     * @throws SeckillException
     */
    public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId, SeckillStateEnum.DATA_REWRITE);
        }
        Date killTime = new Date();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("seckillId", seckillId);
        map.put("phone", userPhone);
        map.put("killTime", killTime);
        map.put("result", null);
        try {
            seckillDao.killByProcedure(map);//当存储过程，执行完之后。result被赋值
            //获取result值
            int result = MapUtils.getInteger(map, "result", -2);//告诉map，需要result属性，如果返回为null，返回为-2.
            if (result == 1) {
                SuccessKilled sk = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, sk);
            } else {
                return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
        }


    }
}
